<template>
  <div class="form-container">
    <smart-form
      ref="formRef"
      :fields="formFields"
      :initial-values="formData"
      @update:modelValue="handleUpdate"
    />

    <div class="form-actions">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const formRef = ref()

// 表单配置
const formFields = [
  {
    type: 'input',
    label: '用户名',
    prop: 'username',
    rules: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' },
    ],
  },
  {
    type: 'select',
    label: '城市',
    prop: 'city',
    options: [
      { label: '北京', value: 'bj' },
      { label: '上海', value: 'sh' },
    ],
    rules: [{ required: true, message: '请选择城市', trigger: 'blur' }],
  },
  {
    type: 'date',
    label: '日期',
    prop: 'date',
    placeholder: '选择日期',
  },
]

// 初始数据
const formData = ref({
  username: '',
  city: '',
  date: '',
})

// 数据更新回调
const handleUpdate = (val: object) => {
  console.log('表单数据更新:', val)
}

// 重置表单
const resetForm = () => {
  formRef.value?.reset()
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    const data = formRef.value?.getFormData()
    console.log('提交数据:', data)
    // 这里可以添加提交逻辑
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 20px auto;
}
.form-actions {
  margin-top: 20px;
  text-align: center;
}
</style>
